import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-12-12
 * Time: 11:09
 */
class Solution1_2 {
    public boolean backspaceCompare(String ss, String tt) {
        Stack<Character> s1 = new Stack<>();
        Stack<Character> t1 = new Stack<>();


        char[] s = ss.toCharArray();
        for(char ch : s){
            if(!s1.isEmpty() && ch == '#'){
                s1.pop();
            }else if(ch != '#'){
                s1.push(ch);
            }
        }

        char[] t = tt.toCharArray();
        for(char ch : t){
            if(!t1.isEmpty() && ch == '#'){
                t1.pop();
            }else if(ch != '#'){
                t1.push(ch);
            }
        }

        if(s1.isEmpty() && t1.isEmpty()){
            return true;
        }

        StringBuffer str1  = new StringBuffer();
        while(!s1.isEmpty()){
            str1.append(s1.pop());
        }

        StringBuffer str2  = new StringBuffer();
        while(!t1.isEmpty()){
            str2.append(t1.pop());
        }
        String x = str1.toString();
        String y = str2.toString();

        return x.equals(y);
    }
}
class Solution1_2_2 {
    public boolean backspaceCompare(String ss, String tt) {
        return changeStr(ss).equals(changeStr(tt));
    }

    // 这个方法是用来模拟栈的出和进
    public String changeStr(String str){
        StringBuffer ret = new StringBuffer();

        for(int i = 0 ; i < str.length() ; i++){
            char ch = str.charAt(i);
            if(ch != '#'){
                ret.append(ch);
            }else if(!ret.isEmpty() && ch == '#'){//ret非空才能删除元素
                int len = ret.length();
                ret.deleteCharAt(len-1);
            }
        }
        return ret.toString();
    }
}


public class Test1_2 {
    public static void main(String[] args) {
        Solution1_2 solution = new Solution1_2();
        solution.backspaceCompare("ab#c","ab#c");
    }
}
